<template>
  <el-dialog 
    :title="dialogTitle" 
    :visible.sync="dialogVisible" 
    width="80%" 
    @close="handleClose"
    custom-class="custom-dialog"
    :close-on-click-modal="false">
    
    <el-form 
      ref="questionForm" 
      :model="formData" 
      :rules="rules" 
      label-width="100px" 
      class="question-form">
      <el-form-item label="题目分类" prop="categoryId" class="form-item-category form-item-question">
        <el-select v-model="formData.categoryId" placeholder="请选择题目分类" clearable style="width: 100%;">
          <el-option
            v-for="item in questionCategories"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #f56c6c;" @click.stop="deleteCategory(item.id)">
              <i class="el-icon-delete"></i>
            </span>
          </el-option>
          <el-option class="add-category-option">
            <div style="display: flex; align-items: center; justify-content: space-between;" @click="showAddCategoryDialog">
              <span>添加分类</span>
              <i class="el-icon-plus" style="color: #409EFF;"></i>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
        <!-- 添加分类对话框 -->
        <el-dialog
          title="添加题目分类"
          :visible.sync="addCategoryDialogVisible"
          width="30%">
          <el-form :model="categoryForm" :rules="categoryRules" ref="categoryForm" label-width="100px">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="categoryForm.name" placeholder="请输入分类名称" style="width: 80%;"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleAddCategory">确 定</el-button>
          </span>
        </el-dialog>
      <!-- 题目类型 -->
      <el-form-item label="题目类型" prop="type" class="form-item-type">
        <el-select 
          v-model="formData.type" 
          placeholder="请选择题目类型"
          style="width: 200px">
          <el-option label="选择题" value="选择题"></el-option>
          <el-option label="填空题" value="填空题"></el-option>
          <el-option label="问答题" value="问答题"></el-option>
        </el-select>
      </el-form-item>

      <!-- 隐藏的答题时间，默认60秒 -->
      <input type="hidden" v-model="formData.answerTime" value="60" />
      
      <!-- 题目文本 - 富文本编辑器 -->
      <el-form-item label="题目内容" prop="questionText" class="form-item-question">
        <rich-text-editor 
          v-model="formData.questionText"
          placeholder="请输入题目内容"
          style="width: 100%; min-height: 200px;"
        />
      </el-form-item>
      
      <!-- 题目答案 - 富文本编辑器 -->
      <el-form-item label="题目答案" prop="answer" class="form-item-answer">
        <rich-text-editor 
          v-model="formData.answer"
          placeholder="请输入标准答案"
          style="width: 100%; min-height: 200px;"
        />
      </el-form-item>
      
      <el-form-item label="答题时间" prop="answerTime">
        <el-input-number 
          v-model="formData.answerTime" 
          :min="1" 
          :max="3600"
          :step="10"
          step-strictly
          controls-position="right"
          style="width: 200px">
        </el-input-number>
        <span class="form-tip">秒</span>
      </el-form-item>
      
      <el-form-item label="默认得分" prop="score">
        <el-input-number 
          v-model="formData.score" 
          :min="0" 
          :max="100"
          :step="1"
          step-strictly
          controls-position="right"
          style="width: 200px">
        </el-input-number>
        <span class="form-tip">分</span>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel" icon="el-icon-close">取消</el-button>
      <el-button type="primary" @click="handleSubmit" icon="el-icon-check">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import RichTextEditor from '@/components/common/RichTextEditor.vue'

export default {
  name: 'EditQuestionDialog',
  components: {
    RichTextEditor
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: () => ({
        type: '选择题',
        questionText: '',
        answer: '',
        answerTime: 60,
        score: 5
      })
    },
    rules: {
      type: Object,
      default: () => ({
        type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
        questionText: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入题目答案', trigger: 'blur' }],
        answerTime: [{ required: true, message: '请设置答题时间', trigger: 'blur' }],
        score: [{ required: true, message: '请设置题目分值', trigger: 'blur' }]
      })
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: this.visible,
      questionCategories: [],
      addCategoryDialogVisible: false,
      categoryForm: {
        name: ''
      },
      categoryRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
        ]
      },
      formData: { ...this.form }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑题目' : '添加新题目'
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal
      if (newVal) {
        this.formData = { ...this.form }
      }
    },
    form: {
      handler(newVal) {
        this.formData = { ...newVal }
      },
      deep: true
    }
  },
  methods: {
    // 加载题目分类
    async loadQuestionCategories() {
      try {
        const res = await this.$http.get('/question-category/list');
        if (res.data.code === 200) {
          this.questionCategories = res.data.data || [];
        }
      } catch (error) {
        console.error('加载题目分类失败:', error);
        this.$message.error('加载题目分类失败');
      }
    },
    
    // 显示添加分类对话框
    showAddCategoryDialog() {
      this.categoryForm.name = '';
      this.addCategoryDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.categoryForm?.clearValidate();
      });
    },
    
    // 添加分类
    async handleAddCategory() {
      try {
        await this.$refs.categoryForm.validate();
        const res = await this.$http.post('/question-category/add', {
          name: this.categoryForm.name
        });
        if (res.data.code === 200) {
          this.$message.success('添加成功');
          this.addCategoryDialogVisible = false;
          await this.loadQuestionCategories();
        }
      } catch (error) {
        console.error('添加分类失败:', error);
        this.$message.error(error.response?.data?.msg || '添加分类失败');
      }
    },
    
    // 删除分类
    async deleteCategory(id) {
      try {
        await this.$confirm('确定要删除该分类吗？', '提示', {
          type: 'warning'
        });
        const res = await this.$http.delete(`/question-category/delete/${id}`);
        if (res.data.code === 200) {
          this.$message.success('删除成功');
          await this.loadQuestionCategories();
          // 如果删除的是当前选中的分类，则清空选择
          if (this.formData.categoryId === id) {
            this.formData.categoryId = null;
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error);
          this.$message.error(error.response?.data?.msg || '删除分类失败');
        }
      }
    },
    
    handleSubmit() {
      this.$refs.questionForm.validate(valid => {
        if (valid) {
          this.$emit('submit', { ...this.formData })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.form-item-type {
  margin-bottom: 20px;
}

.form-item-question,
.form-item-answer {
  margin-bottom: 20px;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}
</style>
